<template>
  <div class="room-chat">
    <div class="room-chat-main">

      <div class="room-groupBox" v-loading="loading">

        <mt-navbar v-model="selected" class="room-groupBox-select">
          <mt-tab-item id="1" disabled="true">群组列表</mt-tab-item>
          <mt-tab-item id="2">我的群组</mt-tab-item>
        </mt-navbar>

        <mt-tab-container v-model="selected" >
          <mt-tab-container-item id="1">
            <mt-cell class="room-groupBox-list" v-for="(item,i) in groupList "
                     :key="i"
                     :title="'['+i+']'+': '+item.groupName">
              <mt-button type="primary" size="small" :disabled="item.inMyGroup" @click.native="joinGroup(item)">
                申请加入
              </mt-button>
            </mt-cell>
          </mt-tab-container-item>
          <mt-tab-container-item id="2">
            <mt-cell class="room-groupBox-list" v-for="(item,i) in myGroupList"
                     :key="i" :title="'['+i+']'+': '+item.groupName"
                     @click.native="enterGroupChat(item.groupId)">
            </mt-cell>

          </mt-tab-container-item>

        </mt-tab-container>

      </div>


        <div v-if="chatBoxVisible" v-model="groupInfo" class="room-chatBox">
            <div class="room-chatBox-topInfo">
              <mt-button type="default" size="small"  @click.native="exitGroupChat" >Exit</mt-button>
              <span style="color: #409EFF ;padding-left: 10px" >
                --{{groupInfo.groupName}}--
                [总人数]: {{groupInfo.groupSize}}
<!--                [在线人数]:{{onlineNum}}-->
              </span>
            </div>

            <div class="room-chatBox-massageBox">
              <div v-for="(item, index) in msgList" :key="index" style="width: 100%">
                  <div :class="item.fromUser === userName ? 'room-msg-my' : 'room-msg-others'">
                    <div class="room-msg-inner-name">[{{roles.toString()}}]{{ item.fromUser }}</div>
                    <div class="room-msg-inner-text">{{ item.content }}</div>
                  </div>
              </div>
            </div>

            <div class="room-chatBox-inputBox">
              <el-input style="width:100%; border: none" size="medium" name="content" v-model="content" placeholder="请输入信息" clearable>
                <el-button @click="sendMsg()" slot="append" style="width:100%; border: none" type="primary" size="medium">发送</el-button>
              </el-input>
            </div>

        </div>
    </div>

  </div>
</template>

<script>
  import { fetchGroupDetail, fetchAllGroup, fetchMyGroup } from '@/api/group'
  import { mapGetters } from 'vuex'
  export default {
    name: 'groupChatRoom',
    components: {},
    data() {
      return {
        data: null,
        selected: '2',
        ws: null,
        loading: false,
        chatBoxVisible: false,
        groupList: [],
        myGroupList:[],
        groupID: '',
        userId: '',
        userName: '',
        groupInfo: null,
        msgList: [],
        content: '',
        onlineNum: 0
      }
    },

    watch:{
      groupList(item1,item2){},
      deep:true
    },

    computed: {
      ...mapGetters([
        'name',
        'roles',
        'authName'
      ]),
    },

    created() {
      this.getMyGroup()
      this.getAllGroupList()
    },


    methods: {
      getAllGroupList() {
        this.loading = true
        fetchAllGroup({}).then(response => {
          const list  = response.data.list
          setTimeout(() => { // 延时渲染
            list.map(v=>{
              this.$set(v,"inMyGroup",false)
              for(let i=0;i<this.myGroupList.length;i++){
                if((v.groupId.toString() == this.myGroupList[i].groupId.toString())){
                  v.inMyGroup = true
                  break
                }
              }
            })
            this.groupList = list
            this.loading=false
          }, 1500);

        }).catch(err => {
          console.log(err)
        });
      },

      getMyGroup(){
        this.userId = this.authName
        this.userName = this.name
        this.myGroupList = []
        this.loading = true
        fetchMyGroup(this.userId).then(response => {
          this.myGroupList = response.data.list
        }).catch(err => {
          console.log(err)
        });
      },

      enterGroupChat(id) {
        this.chatBoxVisible = false
        this.loading = true

        fetchGroupDetail(id).then(response => {
          this.groupInfo = response.data
          this.loading = false

          this.initWebSocket(id)
          this.chatBoxVisible = true
        }).catch(() => {
          this.loading = false
        });
      },

      joinGroup(item){

      },

      exitGroupChat(){
        this.ws.close()
        this.ws = null
        this.groupInfo = null
        this.msgList = []
        this.chatBoxVisible = false
      },

      sendMsg() {
        if (this.content===''){
          this.$message({
            message:'请 输 入 内 容'
          });
          return
        }
        var _this = this
        var params = {
          content: _this.content
        }
        _this.ws.send(JSON.stringify(params))
        this.content = ''
      },

      //初始化 websocket
      initWebSocket(id) {
        this.groupID = id
        var _this = this
        if (window.WebSocket) {
          var url = 'ws://localhost:9527' + '/chat/private/' + this.groupID + '/' + this.userId + '/' + this.userName
          var ws = new WebSocket(url)
          _this.ws = ws

          ws.onopen = function(e) {}

          ws.onmessage = function(e) {
            _this.msgList.push(JSON.parse(e.data))
            _this.onlineNum = JSON.parse(e.data).onlineNum
          }

          ws.onclose = function(e) {
            console.log("退出")
          }
        }
      },
    }
  }
</script>

<style lang="scss">
@import "../_styles/chatRoom-main";
</style>
